package sk.uniza.fri.cerviix.client.graphics;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import org.lwjgl.opengl.GL11;

import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;

public class Texture
{
    private int width;
    private int height;
    private int GLId;

    public Texture(String fileName) throws FileNotFoundException, IOException
    {
        this(new FileInputStream(fileName));
    }
    
    public Texture(InputStream fileInputStream) throws IOException
    {
        PNGDecoder decoder = new PNGDecoder(fileInputStream);

        width = decoder.getWidth();
        height = decoder.getHeight();

        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*width*height);
        decoder.decode(byteBuffer, decoder.getWidth()*4, Format.RGBA);
        byteBuffer.flip();

        GLId = GL11.glGenTextures();
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, GLId);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, byteBuffer);
    }

    public int getGLId()
    {
        return GLId;
    }

    public void bind()
    {
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, getGLId());
    }

    public int getHeight()
    {
        return height;
    }

    public int getWidth()
    {
        return width;
    }
}
